package club.kingyin.kyblogprosearch.controller;

import club.kingyin.commons.clients.PhotoClient;
import club.kingyin.commons.clients.PoetryClient;
import club.kingyin.commons.response.Result;
import club.kingyin.easycache.annotation.EasyCache;
import club.kingyin.kyblogprosearch.trans.TransApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/photo")
public class PhotoController {

    @Resource
    private PhotoClient photoClient;
    @Resource
    private PoetryClient poetryClient;
    @Value("${photo.access-key}")
    private String CLIENT_ID;

    @Resource
    private TransApi transApi;

    @EasyCache(module = "ky-search", timeUnite = TimeUnit.DAYS, time = 24, saveException = false)
    @GetMapping("/random")
    public Result random(@RequestParam("count") int count) {
        String random = photoClient.random(CLIENT_ID, count);
        JSONObject object = JSON.parseObject("{\"res\":"+random+"}");
        return Result.success(object);
    }

    @GetMapping("/search")
    public Result search(@RequestParam("query") String str) {
        if (str.isEmpty()) {
            return Result.infoN("内容为空");
        }
        String transResult = transApi.getTransResult(str, "auto", "en");
        String trans = JSON.parseObject(transResult).getJSONArray("trans_result").getJSONObject(0).getString("dst");
        JSONObject photoResponse = JSON.parseObject(photoClient.query(CLIENT_ID, trans));
        return Result.success(photoResponse);
    }

    @EasyCache(module = "ky-search", timeUnite = TimeUnit.DAYS, time = 24, saveException = false)
    @GetMapping("/poetry")
    public Result poetry() {
        String poetry = JSON.parseObject(poetryClient.getOne()).getJSONObject("data").getString("content");
        Map<String,String> res = new HashMap<>();
        res.put("content",poetry);
        return Result.success(res);
    }
}
